package cn.lefull.service;


import cn.lefull.controller.TestController;
import cn.lefull.redis.RedisRepository;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description:
 * @author: qijiang
 * @date: 2019/3/15 15:32
 */

public class RedisTest implements Runnable{
    private static final String lockKey = "lock";
    private RedisRepository redisRepository;
    public RedisTest(RedisRepository redisRepository) {
        this.redisRepository=redisRepository;
    }
    @Override
    public void run() {
        Thread thread = Thread.currentThread();
        Lock lock =new ReentrantLock();
        for (int i = 0; i < 10; i++) {
            try {
                //必须设置一定时间的休眠，否则所有线程瞬间跑完，不一定会消耗完redis中的数量，不能达到预期的效果
                if(redisRepository.hasKey(lockKey)){
                    Thread.sleep(500);
                }
                if(redisRepository.setIfNotExist(lockKey, "1")){
                    //System.out.println(thread.getName()+"获取了锁");
                    String s = redisRepository.get(TestController.KEY_);
                    System.out.println(s);
                    Integer number = Integer.parseInt(s);
                    if(number >0){
                        System.out.println("-------消耗减1-------");
                        redisRepository.set(TestController.KEY_,String.valueOf(number-1),10000L);
                    }
                    redisRepository.delete(lockKey);
                }
            }catch (Exception e){
                System.out.println("异常");
            }finally {
            }



        }
    }

}
